﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO.jwuct;

namespace Pay.Service {
	public class JwuctSign {
		public JwuctSign() {
		}
#if DEBUG
		private string api_url = "https://117.29.177.242:7201/jwucpay";
		private const string _key = "1234567890";
#else
		private string api_url = "https://pay.jwuct.net:7201/jwucpay";
		private const string _key = "7677ac45cb654a56a8908846e5c1cbba";
#endif
		private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {
			//直接确认，否则打不开
			return true;
		}
		public async Task<T> PayGateway<T>(jwuct_head model) where T : jwuct_base_result, new() {
			var log = IocHelper.Get<ILogHelper>("info");
			var json = model.ToJson();
			log.Info(json);
#if DEBUG
			return new T { resultCode = "00", resCode = "00" };
#else
			try {
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
				var resp = await api_url.PostJsonAsync(model).ReceiveJson<T>();
				log.Info(resp.ToJson());
				return resp;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return default(T);
			}
#endif
		}

		public async Task<string> PayGateway(jwuct_head model) {
			var log = IocHelper.Get<ILogHelper>("info");
			var json = model.ToJson();
			log.Info(json);
#if DEBUG
			return "test";
#else
			try {
				ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
				var resp = await api_url.PostJsonAsync(model).ReceiveString();
				if (resp.IsJsonStart()) {
					var msg = resp.ToObject<jwuct_base_result>();
					return "FAIL" + msg.resDesc;
				}
				return resp;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
#endif
		}

		/// <summary>
		/// 请求通道封装sign.
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		public string Sign(jwuct_head model, params string[] filter) {
			string json = model.ToJson();
			var collection = json.ToObject<SortedDictionary<string, object>>();
			collection.Remove("sign");
			if (filter != null) {
				foreach (var f in filter)
					collection.Remove(f);
			}
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&') + "&key=" + _key;
			var log = IocHelper.Get<ILogHelper>("info");
			log.Error(result);

			result = SecureHelper.MD5(result).ToUpper();
			return result;
		}
		/// <summary>
		/// 验证sign.
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		public bool VerifySign(JObject model) {
			var collection = model.ToObject<SortedDictionary<string, object>>();
			var sign = collection["sign"].ToString();
			collection.Remove("sign");
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&') + "&key=" + _key;
			Console.WriteLine(result);
			result = SecureHelper.MD5(result).ToUpper();
			Console.WriteLine(result);
			return result == sign;
		}

		/// <summary>
		/// test
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		/// <param name="filter">Filter.</param>
		public string Sign(jwuct_notity model, params string[] filter) {
			string json = model.ToJson();
			var collection = json.ToObject<SortedDictionary<string, object>>();
			collection.Remove("sign");
			if (filter != null) {
				foreach (var f in filter)
					collection.Remove(f);
			}
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&') + "&key=" + _key;
			result = SecureHelper.MD5(result).ToUpper();
			return result;
		}
	}
}
